<?php
/**
 * user相关的model实现
 * @文件名称: UserModel.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\modules\user\models\user;
use app\base\BaseModel;
use Yii;
use app\components\DmpLog;

class UserModel extends BaseModel
{
    public static function tableName()
    {
        return '{{%user}}';
    }
    public static $s_fields = [
        'id',
        'user_name',
        'user_pwd',
        'structure_id',
        'group_id',
        'salt',
        'create_time',
        'update_time',
        'status',
        'remark',
        'role_ids',
    ];

    /**
     * 更新用户信息数据
     * @param int $user_id 用户ID
     * @param array $updateInfo 用户需要更新的数据集合
     * @return bool
     */
    public static function updateUserData($user_id, $updateInfo) {
        try {
            $updateData = [];
            $isFields = false;
            foreach($updateInfo as $key => $v) {
                if(in_array($key, self::$s_fields)) {
                    $isFields = true;
                    $updateData[$key] = $v;
                }
            }
            if(empty($updateData) || empty($user_id) || !$isFields) {
                return false;
            }
            $userinfo = self::findIdentity($user_id);
            if(isset($updateData['user_pwd'])) {
                $userinfo ->user_pwd =  trim($updateData['user_pwd']);//密码
            }
            if(isset($updateData['structure_id'])) {
                $userinfo ->structure_id =  (int)$updateData['structure_id'];//所属组织架构ID
            }
            if(isset($updateData['group_id'])) {
                $userinfo ->group_id =  (int)$updateData['group_id'];//所属集团ID
            }
            if(isset($updateData['salt'])) {
                $userinfo ->salt =  trim($updateData['salt']);//创建账号时系统随机分配的密码加密盐值
            }
            if(isset($updateData['status'])) {
                $userinfo ->status =  (int)$updateData['status'];//账号状态
            }
            if(isset($updateData['remark'])) {
                $userinfo ->remark =  trim($updateData['remark']);//备注
            }
            if(isset($updateData['role_ids']) && is_array($updateData['role_ids'])) {
                $userinfo ->role_ids =  json_encode($updateData['role_ids']);//角色id数组逗号分隔字符串
            }
            return $userinfo->save();
        } catch (\Exception $e) {
            $log = [
                'msg'    => $e->getMessage(),
                'data' => $updateInfo,
            ];
            DmpLog::log('update_user_data_exception', 'error', $log);
            return false;
        }
    }
    /**
     * 根据主键id获取数据信息
     * @param $id
     * @return static
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }
}
